package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.Page;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetMealController {
    
    @Reference
    private SetMealService setMealService;

    @Autowired
    private JedisPool jedisPool;
    
    //上传图片
    @RequestMapping("/upload")
    public Result uploadPicture(MultipartFile imgFile){
        //使用七牛云工具类完成文件上传
        //1.拼凑文件名
        String originalFilename = imgFile.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String fileSuffix= originalFilename.substring(index - 1);
        String ranStr = UUID.randomUUID().toString();
        String fileName = ranStr + fileSuffix;
        //2.上传文件
        try {
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            //将图片信息添加到redis中保存
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);

            return new Result(true,MessageConstant.UPLOAD_SUCCESS,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }


    //添加新的检查套餐
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){

        try {
            setMealService.addNewSetMeal(setmeal,checkgroupIds);
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
    }

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){

        /*Page<Setmeal> page = setMealService.findPage(queryPageBean);

        System.out.println("setMealController ----"+page.getTotal());

        return new PageResult(page.getTotal(),page.getResult());*/


            return setMealService.findPage(queryPageBean);
    }
    
}
